﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

namespace ProjectSem40701
{
    public partial class Test2 : System.Web.UI.Page
    {
        //diem thi
        double mark = 0;

        //khai bao mot so hang so ve trang thai cua user
        private const int Unknow_Error = 0;
        private const int Exist_In_User_Round_But_InActive = 1;
        private const int Not_Exist_In_User_Round = 2;
        private const int Exist_In_User_Round_AndActive = 3;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Lay ra vong thi hien tai
                GetCurrentRoundExam();

                //Lay ra user name dang nhap vao
                string strUser = System.Web.HttpContext.Current.User.Identity.Name;
                if (strUser == String.Empty)//Neu nguoi dung chua dang nhap
                {
                    //Bao chua dang nhap
                    this.MultiView1.ActiveViewIndex = 0;
                    this.lblError.Text = "Bạn chưa đăng nhập.";
                }
                else
                {
                    //Neu ton tai ky thi duoc active
                    if (IsExistExam())
                    {
                        //kiem tra co ton tai vong thi hay khong
                        if (IsExistRound(Convert.ToInt32(Session["examID"])))
                        {
                            //kiem tra xem user co duoc phep vao thi hay khong
                            switch (IsValidUser())
                            { 
                                case Not_Exist_In_User_Round:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Bạn không đủ điều kiện tham dự vòng thi này.";
                                    break;
                                case Exist_In_User_Round_But_InActive:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Bạn đã tham dự vòng thi này hoặc không được quyền tham dự vòng thi này.";
                                    break;
                                case Unknow_Error:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Lỗi không xác định.";
                                    break;
                                case Exist_In_User_Round_AndActive:
                                        //chuyen sang view preload
                                        this.MultiView1.ActiveViewIndex = 1;
                                    break;
                                default:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Lỗi không xác định.";
                                    break;

                            }
                        }
                        //neu khong co vong thi nao duoc active dang ton tai
                        else
                        {
                            //bao khong co vong thi nao ton tai    
                            this.MultiView1.ActiveViewIndex = 0;
                            this.lblError.Text = "Không có vòng thi nào được kích hoạt.";
                        }
                    }
                    //Neu khong
                    else
                    {
                        //bao khong co ky thi nao ton tai    
                        this.MultiView1.ActiveViewIndex = 0;
                        this.lblError.Text = "Không có kỳ thi nào được kích hoạt.";
                    }
                }
                
            }
        }

        //Lay thong tin ky thi hien tai
        private void GetCurrentRoundExam()
        {
            try
            {
                MainDataset.RoundExamActiveTableAdapters.tbl_Round_Exam_Select_RoundName_ExamName_ActiveTableAdapter dp =
                    new MainDataset.RoundExamActiveTableAdapters.tbl_Round_Exam_Select_RoundName_ExamName_ActiveTableAdapter();
                DataTable dttbl = dp.Get_tbl_Round_Exam_Select_RoundName_ExamName_Active();
                if (dttbl.Rows.Count > 0)
                {
                    string currentRound = "Kỳ thi hiện tại: " + dttbl.Rows[0]["ExamName"] +
                        " - " + dttbl.Rows[0]["RoundName"] + "<br />";
                    this.lblCurrentRoundError.Text = currentRound;
                    this.lblCurrentRoundActive.Text = currentRound;
                }
            }
            catch
            {
                this.lblCurrentRoundError.Text = String.Empty;
                this.lblCurrentRoundActive.Text = String.Empty;
            }
        }
       
        //Kiểm tra xem có kỳ thi nào active đang tồn tại hay không
        private bool IsExistExam()
        {
            bool ok = false;
            try
            {
                MainDataset.ExamTableAdapters.tbl_ExamTableAdapter dpExam = new
                        MainDataset.ExamTableAdapters.tbl_ExamTableAdapter();
                DataTable dttblExam = dpExam.Get_tbl_Exam_Select_All_Status_Active();

                //Neu ton tai exam voi status active
                if (dttblExam.Rows.Count > 0)
                {
                    Session["examID"] = dttblExam.Rows[0]["ExamID"].ToString();
                    ok = true;
                }
                else
                {
                    Session["examID"] = String.Empty;
                    ok = false;
                }
            }
            catch
            {
                ok = false;
            }
            return ok;  
        }
        
        //Kiểm tra xem có vòng thi nào active đang tồn tại hay không
        private bool IsExistRound(int examID)
        {
            bool ok = false;
            try
            {
                MainDataset.RoundTableAdapters.tbl_RoundTableAdapter dpRoundActive = new
                   MainDataset.RoundTableAdapters.tbl_RoundTableAdapter();
                DataTable dttblRoundActive =
                    dpRoundActive.Get_tbl_Round_Select_All_Active_By_ExamID(examID);

                if (dttblRoundActive.Rows.Count > 0)
                {
                    ok = true;
                    Session["roundID"] = dttblRoundActive.Rows[0]["RoundID"].ToString();
                    Session["roundIsFirst"] = dttblRoundActive.Rows[0]["RoundIsFirst"].ToString();
                    Session["roundDuration"] = dttblRoundActive.Rows[0]["RoundDuration"].ToString();
                    Session["roundStartTime"] = dttblRoundActive.Rows[0]["RoundStartTime"].ToString();
                    Session["roundEndTime"] = Convert.ToDateTime(Session["roundStartTime"].ToString()).AddMinutes(
                        Convert.ToDouble(Session["roundDuration"].ToString())).ToString();
                }
                else
                {
                    ok = false;
                }
            }
            catch
            {
                ok = false;
            }
            return ok;
        }
        
        //check xem user co duoc phep vao thi hay khong
        private int IsValidUser()
        {
            Util.CheckValidUser objCheckValidUser = new Util.CheckValidUser();
            int ok = Unknow_Error;
            try
            {
                string strUser = System.Web.HttpContext.Current.User.Identity.Name;
                Guid userID = new Guid(Membership.GetUser(strUser).ProviderUserKey.ToString());
                int rid = Convert.ToInt32(Session["roundID"].ToString());
                MainDataset.UserRoundTableAdapters.tbl_UserRound_Select_All_AllowTest_By_UserIDTableAdapter dp = 
                    new MainDataset.UserRoundTableAdapters.tbl_UserRound_Select_All_AllowTest_By_UserIDTableAdapter();
                DataTable dttblUserRound = dp.Get_tbl_UserRound_Select_All_By_UserID_RoundID(userID, rid);
                
                //Neu ton tai user id va roundid trong bang userround
                if (dttblUserRound.Rows.Count > 0)
                {
                    if (Convert.ToInt32(dttblUserRound.Rows[0]["Status"].ToString()) == 1)
                    {
                        //ton tai trong bang userround va trang thai duoc kich hoat ==> duoc phep vao thi
                        ok = Exist_In_User_Round_AndActive;
                    }
                    else
                    {
                        //Ko ton tai trong bang userround va trang thai duoc kich hoat ==> Ko duoc phep vao thi
                        ok = Exist_In_User_Round_But_InActive;
                    }
                }
                //user va roundid ko ton tai trong bang userround
                else
                {
                    ok = Not_Exist_In_User_Round;
                }
            }
            catch
            {
                ok = Unknow_Error;
            }
            return ok;
        }
        
        //Su kien xay ra khi view pre-load duoc kich hoat
        protected void ViewPreLoadData_Activate(object sender, EventArgs e)
        {
            //neu chua den gio thi
            if (DateTime.Compare(DateTime.Now, Convert.ToDateTime(Session["roundStartTime"].ToString())) < 0)
            {
                //kich hoat dem gio
                this.countDownTimerStartTime.Enabled = true;
            }
            
            //neu da den gio thi hoac het gio thi
            else
            {
                //neu da qua thoi diem ket thuc vong thi
                if (DateTime.Compare(DateTime.Now, Convert.ToDateTime(Session["roundEndTime"].ToString())) > 0)
                {
                    //bao het gio
                    this.MultiView1.ActiveViewIndex = 0;
                    this.lblError.Text = "Thời gian làm bài thi đã kết thúc.";
                }
                else
                {
                    //Chuyen sang view load bai thi
                    this.MultiView1.ActiveViewIndex = 2;
                }
            }
        }

        //su kien xay ra khi view lam bai thi duoc kich hoat
        protected void ViewLoadData_Activate(object sender, EventArgs e)
        {
            string rid = Session["roundID"].ToString();
            BindDataTogrvQA(Convert.ToInt32(rid));
        }

        //Bind du lieu vao grvQA
        private void BindDataTogrvQA(int rid)
        {
            try
            {
                MainDataset.QuestionTableAdapters.tbl_QuestionTableAdapter dpQ = new
                   MainDataset.QuestionTableAdapters.tbl_QuestionTableAdapter();
                DataTable dttbl = dpQ.Get_tbl_Question_Select_All_By_RoundID(rid);
                grvQA.DataSource = dttbl;
                grvQA.DataBind();
                string duration = Session["roundDuration"].ToString();
                this.ltrTotalTime.Text = duration + " phút";
            }
            catch
            { 
                //thong bao loi
            }
        }

        //Dem nguoc thoi gian den luc bat dao vong thi
        protected void countDownTimerStartTime_Tick(object sender, EventArgs e)
        {
            TimeSpan timeRemain = DateTime.Now.Subtract(Convert.ToDateTime(Session["roundStartTime"].ToString()));
            this.lblTimeRemain.Text = "Còn " + timeRemain.Days.ToString() + " ngày " + timeRemain.Hours + " giờ " + timeRemain.Minutes + " phút " + timeRemain.Seconds + " giây ";
            
            //Neu gio hien tai lon hon hoac bang voi start time
            if (DateTime.Compare(DateTime.Now, Convert.ToDateTime(Session["roundStartTime"].ToString())) >= 0)
            { 
                //Chuyen sang view load bai thi
                this.MultiView1.ActiveViewIndex = 2;
            }
        }

        protected void ltrContent_DataBinding(object sender, EventArgs e)
        {
            Literal lblContent = sender as Literal;
            lblContent.Text = Server.HtmlDecode(lblContent.Text.Trim());
        }

        protected void chkbCorrect_DataBinding(object sender, EventArgs e)
        {
            CheckBox chkbCorrect = sender as CheckBox;
            chkbCorrect.Text = Server.HtmlDecode(chkbCorrect.Text.ToString());
        }

        //khi nguoi dung an nut submit bai thi
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            CalculateMark();
        }

        //------------------Chấm điểm ở đây---------------------//

        private void CalculateMark()
        {
            try
            {
                for (int i = 0; i < this.grvQA.Rows.Count; i++)
                {
                    int questionID;
                    ArrayList ansIDs = new ArrayList();
                    double questionMark;
                    ArrayList ansIDsCorrect = new ArrayList();

                    Literal ltrMark = grvQA.Rows[i].FindControl("ltrMark") as Literal;
                    Label lblQID = grvQA.Rows[i].FindControl("lblQID") as Label;
                    GridView grvAns = grvQA.Rows[i].FindControl("grvAnswer") as GridView;

                    questionID = Convert.ToInt32(lblQID.Text);
                    questionMark = Convert.ToDouble(ltrMark.Text);

                    for (int j = 0; j < grvAns.Rows.Count; j++)
                    {
                        CheckBox chkbCorrect = (CheckBox)grvAns.Rows[j].FindControl("chkbCorrect");
                        Literal ltrAnsID = grvAns.Rows[j].FindControl("ltrAnsID") as Literal;
                        if (chkbCorrect.Checked == true)
                        {
                            ansIDs.Add(ltrAnsID.Text);
                        }
                    }

                    MainDataset.AnswerTableAdapters.tbl_Answer_Select_AnswerCorrect_By_QuestionIDTableAdapter dpAnswCorrect =
                        new MainDataset.AnswerTableAdapters.tbl_Answer_Select_AnswerCorrect_By_QuestionIDTableAdapter();
                    DataTable dttblAnswCorrect = dpAnswCorrect.Get_tbl_Answer_Select_AnswerCorrect_By_QuestionID(questionID);

                    for (int j = 0; j < dttblAnswCorrect.Rows.Count; j++)
                    {
                        ansIDsCorrect.Add(dttblAnswCorrect.Rows[j]["AnswerID"].ToString());
                    }

                    if (compareArrlst(ansIDs, ansIDsCorrect) == true)
                    {
                        this.mark += questionMark;
                    }
                }
                SaveMark(mark);
            }
            catch
            {
                //thong bao loi
            }
        }

        //Lưu điểm vào db ở đây

        private void SaveMark(double mark)
        {
            string strUser = System.Web.HttpContext.Current.User.Identity.Name;
            Guid userID = new Guid(Membership.GetUser(strUser).ProviderUserKey.ToString());

            //Luu diem vao database o day
            this.MultiView1.ActiveViewIndex = 3;
            this.lblComplete.Text = "Điểm của bạn đã được lưu vào cơ sở dữ liệu của chúng tôi. Kết quả sẽ được thông báo cho bạn sớm.";
            int rid = Convert.ToInt32(Session["roundID"].ToString());

            MainDataset.UserRoundTableAdapters.tbl_UserRound_Select_All_AllowTest_By_UserIDTableAdapter dpUserRound
                = new MainDataset.UserRoundTableAdapters.tbl_UserRound_Select_All_AllowTest_By_UserIDTableAdapter();
            DataTable dttblUserRound = dpUserRound.Get_tbl_UserRound_Select_All_By_UserID_RoundID(userID, rid);
            if (dttblUserRound.Rows.Count > 0)
            {
                //Update
                dpUserRound.tbl_UserRound_Update_By_UserID_RoundID(mark, userID, DateTime.Now, rid);
            }
            else
            {
                //Insert
                dpUserRound.tbl_UserRound_Insert(userID, rid, mark, DateTime.Now, 0);
            }

        }

        //so sánh arraylist chứa câu trả lời người dùng chọn và arraylist chứa đáp án đúng
        private bool compareArrlst(ArrayList arr1, ArrayList arr2)
        {
            bool ok = false;
            if (arr1.Count != arr2.Count)
            {
                ok = false;
            }
            else
            {
                for (int i = 0; i < arr1.Count; i++)
                {
                    string meo = arr1[i].ToString();
                    string cho = arr2[i].ToString();
                    if (meo != cho)
                    {
                        ok = false;
                        break;
                    }
                    else
                    {
                        ok = true;
                    }
                }
            }
            return ok;
        }
        
        //timer tick, de bat het gio, khi het gio se tu dong submit bai thi
        protected void timerCountDown_Tick(object sender, EventArgs e)
        {
            try
            {
                TimeSpan dtRemain = Convert.ToDateTime(Session["roundEndTime"]).Subtract(DateTime.Now);
                this.ltrTimeRemain.Text =
                    (dtRemain.Hours > 9 ? dtRemain.Hours.ToString() : "0" + dtRemain.Hours.ToString()) + " : " +
                    (dtRemain.Minutes > 9 ? dtRemain.Minutes.ToString() : "0" + dtRemain.Minutes.ToString()) + " : " +
                    (dtRemain.Seconds > 9 ? dtRemain.Seconds.ToString() : "0" + dtRemain.Seconds.ToString());
                if (dtRemain.TotalSeconds <= 0)
                {
                    CalculateMark();
                    if (this.timerCountDown.Enabled == true)
                    {
                        this.timerCountDown.Enabled = false;
                    }
                }
            }
            catch
            {
                //thông báo lỗi
            }
        }
        /// <summary>
        /// 
        /// </summary>
        protected void grvQA_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i < grvQA.Rows.Count; i++)
            {
                Literal ltrQuestionTittle = grvQA.Rows[i].FindControl("ltrQuestionTittle") as Literal;
                ltrQuestionTittle.Text = "Câu " + (i + 1) + ": ";

                GridView grvAns = grvQA.Rows[i].FindControl("grvAnswer") as GridView;
                grvAns.DataBind();
            }
        }
    }
}
